﻿#include "commthread.h"

#include <QList>
#include <QStringList>
#include <QFile>
#include <QDir>
#include "qtcsv/reader.h"
#include "qtcsv/writer.h"
#include "qtcsv/stringdata.h"

#include <QDebug>

#define UDP_PORT (5000)
#define ECHO_IP_ADDR ("127.0.0.1")
#define UART_PORT ("/dev/ttyACM0")
#define HISTORY_FILE ("/home/playpeng/QtPrjTest/testcomm/history.csv")

QList<QStringList> ReadHistory(void)
{
    QString filePath = HISTORY_FILE;
    QList<QStringList> readat = QtCSV::Reader::readToList(filePath);
    return readat;
}

/* the Protocol for data Aggretion */
void ComThread::udpReadDataGrams(void)
{
    if (udp_server != nullptr) {
        while(udp_server->hasPendingDatagrams()) {
            QByteArray data_read;
            QByteArray data_send;

            data_read.resize(udp_server->pendingDatagramSize());
            udp_server->readDatagram(data_read.data(), data_read.size());
            if (data_read.size() > 0) {
                printf("#### UDP收到数据\n");
                if ((data_read.at(0) == 'H') &&
                    (data_read.at(1) == 'I')) {
                    qDebug() << "发送历史数据...";
                    //发送历史数据
                    QList<QStringList> his_data = ReadHistory();
                    qDebug() << "数据大小： " << his_data.size();
                    int start_pos = his_data.size() > 50 ? his_data.size() - 50: 0;
                    for (int i = start_pos; i < his_data.size(); i++) {
                        data_send.clear();
                        data_send.append(QString::number(i) + "," + his_data.at(i).join(","));
                        qDebug() << "发送： " << data_send;
                        udp_send->writeDatagram(data_send);
                    }
                }
            }
        }
    }
}

ComThread::ComThread()
{
    if (udp_server == nullptr) {
        udp_server = new QUdpSocket(this);
        udp_server->bind(UDP_PORT, QUdpSocket::ShareAddress);
        connect(udp_server, &QUdpSocket::readyRead, this, &ComThread::udpReadDataGrams);
    }

    if (udp_send == nullptr) {
        udp_send = new QUdpSocket(this);
        QHostAddress * bcast = new QHostAddress(ECHO_IP_ADDR);
        udp_send->connectToHost(*bcast, 5000, QIODevice::WriteOnly);
        QByteArray data = "hello!";
        udp_send->writeDatagram(data);
    }

    if (commPort == nullptr) {
        commPort = new QSerialPort();
        commPort->setPortName(UART_PORT); //485通信串口
        commPort->setBaudRate(9600);
        commPort->setFlowControl(QSerialPort::NoFlowControl);
        commPort->setParity(QSerialPort::NoParity);
        commPort->setDataBits(QSerialPort::DataBits::Data8);
        commPort->setStopBits(QSerialPort::StopBits::OneStop);
        commPort->open(QIODevice::ReadWrite);
        commPort->moveToThread(this);
    }
}

void ComThread::run()
{
    QByteArray datasnd;
    QByteArray readata;

    while (1) {
        if (commPort != NULL) {
            commPort->waitForReadyRead(200);
            readata = commPort->readAll();
            if (readata.size() >= 2) {
                printf("485 com read size = %d\n", readata.size());
                printf("485 com read 0 = 0x%02X\n", readata.at(0));
                printf("485 com read 0 = 0x%02X\n", readata.at(1));
                qDebug() << "485 READ: size = " << readata.size() << "data: " << readata.data();
            }

            if (readata.size() >= 2) {
                if ((readata[0] == 'H') &&
                    (readata[1] == 'I')) {
                    //发送历史数据
                    QList<QStringList> his_data = ReadHistory();

                    int start_pos = his_data.size() > 50 ? his_data.size() - 50: 0;
                    for (int i = start_pos; i < his_data.size(); i++) {
                        datasnd.clear();
                        datasnd.append(QString::number(i) + his_data.at(i).join(",") + "\n");
                        commPort->write(datasnd);
                        commPort->waitForBytesWritten(500);
                        qDebug() << "485 WRITE: " << datasnd.data();
                    }
                }
            }
        }

        QThread::msleep(1000);
    }
}
